package com.db.chat.server;

import java.io.*;
import java.net.Socket;

/**
 * Created by Student on 25.11.2014.
 */
public class Transport implements Closeable{
    private DataInputStream is;
    private DataOutputStream os;
    private Socket socket;
    private String roomName;

    public String getRoomName() {
        return roomName;
    }

    public void setRoomName(String roomName) {
        this.roomName = roomName;
    }

    private volatile boolean markedForDeletion = false;

    public Transport(Socket socket) throws IOException {
        this.is = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
        this.os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
        this.socket = socket;

        roomName = new String("guest-room");
    }

    public void send(String str) throws TransportException {
        synchronized (os) {
            try {
                os.writeUTF(str);
                os.flush();
            } catch (IOException e) {
                throw new TransportException(e);
            }
        }
    }

    public String receive() throws TransportException {
        synchronized (is) {
            try {
                return is.readUTF();
            } catch (IOException e) {
                throw new TransportException(e);
            }
        }
    }

    @Override
    public void close() throws TransportException {
        try {
            os.close();
            is.close();
            socket.close();
        } catch (IOException e) {
            throw new TransportException(e);
        }
    }

    public boolean getMarked() {
        return markedForDeletion;
    }
    public void markForDeletion() {this.markedForDeletion = true; };
}
